//
//  TestPlanViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/7/10.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "TestPlanViewController.h"
#import "TestPlanCell.h"
#import "AddClassOrCNView.h"
#import "BeginNewPlanViewController.h"
#import "TestPlanDataViewController.h"
#import "ContinuePlanViewController.h"
@interface TestPlanViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong) PlanModel * planModel;
@property (nonatomic,strong) NSMutableArray * planArray;
@property (nonatomic,strong) AddClassOrCNView * changeNameView;
@property (nonatomic,strong)BaseAlertView * alertView;
@property (nonatomic,strong) NSMutableArray * joinNumberArray;
@property (nonatomic,strong) NSMutableDictionary * allDataDictionary;
@property (nonatomic,assign) NSInteger joinProNumber;
@property (nonatomic,strong) UILabel * noDataLabel;
@property (nonatomic,assign) NSInteger Rinteger;
@end

@implementation TestPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"测试计划";
    //添加键盘监听事件
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShoww:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHidee:) name:UIKeyboardWillHideNotification object:nil];
    self.view.backgroundColor = UIColorFromRGB(241, 244, 248);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 35,35);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
    //创建右边按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 170,35);
    rightBtn.layer.cornerRadius =10;
    rightBtn.backgroundColor = [UIColor whiteColor];
    //    [rightBtn setImage:[UIImage imageNamed:@"navRightBtn"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"十 新建测试计划" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [rightBtn setTitleColor:UIColorFromRGB(26, 167, 157) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItemm = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItemm.width = -5;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.rightBarButtonItems = @[spaceItemm,rightBarBtn];
    
}

-(void)viewWillAppear:(BOOL)animated{
    if (self.myTableView !=nil) {
        [self.myTableView removeFromSuperview];
    }
    if (self.noDataLabel !=nil) {
        [self.noDataLabel removeFromSuperview];
    }
    [self getData];
}

//获取数据
-(void)getData{
    self.planArray =[[NSMutableArray alloc]init];
    NSMutableArray * projectIDarray = [[NSMutableArray alloc]initWithCapacity:0];//存放当前拥有计划的ID ，用以查询有多少人在这个计划中
    self.joinNumberArray = [[NSMutableArray alloc]initWithCapacity:0];//存放每个计划有多少人参加
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //取出Programs   PLAN 模型加入数组
    NSMutableArray * userPlanArr = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"Programs"]];
//    //根据创建时间倒序排列
//    NSLog(@"s1");
//    for (int  i =0; i<[userPlanArr count]-1; i++) {
//        
//        for (int j = i+1; j<[userPlanArr count]; j++) {
//            NSMutableDictionary * dic = userPlanArr[i];
//            NSString * birthStr = [[dic objectForKey:@"CreateTime"] substringWithRange:NSMakeRange(0, 10)];
//            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//            NSDate *birthDate = [dateFormatter dateFromString:birthStr];
//            NSString * realAge = [self dateToDetailOld:birthDate];
//            NSMutableDictionary * dict = userPlanArr[j];
//            NSString * birthStr1 = [[dict objectForKey:@"CreateTime"] substringWithRange:NSMakeRange(0, 10)];
//            NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
//            [dateFormatter1 setDateFormat:@"yyyy-MM-dd"];
//            NSDate *birthDate1 = [dateFormatter1 dateFromString:birthStr1];
//            NSString * realAge1 = [self dateToDetailOld:birthDate1];
//            
//            if ([realAge intValue]>[realAge1 intValue]) {
//                
//                //交换
//                
//                [userPlanArr exchangeObjectAtIndex:i withObjectAtIndex:j];
//                
//            }
//            
//        }
//        
//    }
//    NSLog(@"s2");
//
    
    //将负数放在最前面
    for (NSMutableDictionary * dict in userPlanArr.reverseObjectEnumerator) {
        if ([[dict objectForKey:@"Id"]integerValue]<0) {
            [userPlanArr removeObject:dict];
            [userPlanArr insertObject:dict atIndex:0];
        }
    }
    for (NSMutableDictionary * dic in userPlanArr) {
        if (![[dic objectForKey:@"Type"]isEqual:@0]) {
//            NSNumber * nonum = [NSNumber numberWithBool:NO];
//            [dic setObject:nonum forKey:@"Status"];
            PlanModel * model = [PlanModel modelWithDictionary:dic];
            [self.planArray addObject:model];
            [projectIDarray addObject:model.Id];
        }
        
    }
    //循环遍历看有多少人参加了现有的计划
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
    NSMutableArray * childArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"ChildList"]];
    for (NSNumber * num in projectIDarray) {
        NSInteger joinProNumber = 0;
//        for (NSMutableDictionary * childDic in childArray) {
        
            for (NSDictionary * dict in testArray) {
                NSDictionary * masterdic = [dict objectForKey:@"master"];
                
//                if ([[childDic objectForKey:@"Id"]isEqual:[masterdic objectForKey:@"ChildId"]]) {
                
                    if ([[masterdic objectForKey:@"ProgramId"]isEqual:num]) {
                        joinProNumber += 1;
                    }
                }
//            }
        
//        }
        NSNumber * joinNum = [NSNumber numberWithInt:joinProNumber];
        [self.joinNumberArray addObject:joinNum];
    }

    [user synchronize];
    [self setUI];
}

-(void)setUI{
    
    self.myscrollView = [[UIScrollView alloc]init];
    self.myscrollView.backgroundColor =UIColorFromRGB(241, 244, 248);
    self.myscrollView.showsVerticalScrollIndicator = NO;
    self.myscrollView.contentSize = CGSizeMake(0, 1000);
    [self.view addSubview:self.myscrollView];
    [self.myscrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    
    if (self.planArray.count ==0) {
        _noDataLabel = [[UILabel alloc]init];
        _noDataLabel.text = @"还没有测试计划";
        _noDataLabel.textColor = [UIColor blackColor];
        _noDataLabel.font = [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal];
        [self.view addSubview:_noDataLabel];
        [_noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.centerY.mas_equalTo(self.view.mas_centerY);
            
        }];
    }else{
    
    self.myTableView = [[UITableView alloc]init];
    self.myTableView.backgroundColor =UIColorFromRGB(241, 244, 248);
    self.myTableView.delegate =self;
    self.myTableView.dataSource =self;
    self.myTableView.showsVerticalScrollIndicator =NO;
    //无分割线
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //多余的CELL 隐藏
    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.myTableView registerClass:[TestPlanCell class] forCellReuseIdentifier:@"TestPlanCell"];
    [self.myscrollView addSubview:self.myTableView];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.myscrollView.mas_top).with.offset(40*AutoScaleVertical);
        make.left.mas_equalTo(self.myscrollView.mas_left).with.offset(75*AutoScaleHorizontal);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-75*AutoScaleHorizontal);
        make.height.mas_equalTo(85*self.planArray.count*AutoScaleVertical);
    }];
    }
    self.myscrollView.contentSize = CGSizeMake(0, (self.planArray.count*85+85)*AutoScaleVertical);
    

}

#pragma mark tableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85*AutoScaleVertical;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.planArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TestPlanCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TestPlanCell"];
    //cell.userInteractionEnabled = NO;
    if (cell == nil) {
        cell = [[TestPlanCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: @"TestPlanCell"] ;
        //        cell.selectedBackgroundView.backgroundColor = [HexColor colorWithHexString:@"#00bcab"];
        //        cell.textLabel.highlightedTextColor = [HexColor colorWithHexString:@"#fffff"];
    }
    
    [cell relayoutCellWithModel:self.planArray[indexPath.row] andIndex:indexPath.row andArrCount:self.planArray.count andJoinNum:self.joinNumberArray[indexPath.row]];
    __weak typeof(self) weak_self = self;
    cell.callEdit = ^(NSInteger index) {
        NSLog(@"开始编辑%d",index);
        [weak_self ChangeCLassNameWith:index];
    };
    cell.callDelete = ^(NSInteger index) {
        NSLog(@"开始删除%d",index);
        [weak_self creatDeleteViewWithIndex:index];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PlanModel * model = self.planArray[indexPath.row];
    if (model.Status ==YES) {
        TestPlanDataViewController * dvc = [[TestPlanDataViewController alloc]init];
        dvc.planModel = model;
        [self.navigationController pushViewController:dvc animated:YES];
    }else{
        ContinuePlanViewController * cpvc = [[ContinuePlanViewController alloc]init];
        cpvc.ownModel = model;
        [self.navigationController pushViewController:cpvc animated:YES];
    }
    
    
}

#pragma mark  删除计划
-(void)creatDeleteViewWithIndex:(NSInteger)indexpath{
    self.Rinteger = indexpath;
    PlanModel * mod = self.planArray[indexpath];
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    
    _alertView = [[BaseAlertView alloc]init];
    _alertView.infomationLabel.text = @"是否删除该测试计划?";
    [window addSubview:_alertView];
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(window.mas_centerX);
        make.centerY.mas_equalTo(window.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(500*AutoScaleHorizontal, 250*AutoScaleVertical));
    }];
    
    UILabel * planname = [[UILabel alloc]init];
    planname.text =[NSString stringWithFormat:@"测试计划:%@",mod.Title];
    [planname setTextAlignment:NSTextAlignmentCenter];
    planname.textColor = UIColorFromRGB(81, 81,81);
    planname.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [_alertView addSubview:planname];
    [planname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_alertView.infomationLabel.mas_bottom).with.offset(5*AutoScaleVertical);
        make.centerX.mas_equalTo(_alertView.infomationLabel.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(400*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    [_alertView.yesBtn addTarget:self action:@selector(pressAlertYesWithindex:) forControlEvents:UIControlEventTouchUpInside];
    [_alertView.noBtn addTarget:self action:@selector(pressAlertNo) forControlEvents:UIControlEventTouchUpInside];
}
-(void)pressAlertYesWithindex:(NSInteger)indexpath{
    NSLog(@"确定删除");
    indexpath = self.Rinteger;
    PlanModel * mod = self.planArray[indexpath];
    for (PlanModel * model in self.planArray.reverseObjectEnumerator) {
        if (model == mod) {
            [self.planArray removeObject:model];
        }
    }
    //更新数据源
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSMutableArray * arr = [_allDataDictionary objectForKey:@"Programs"];
    NSMutableDictionary * dic = arr[indexpath];
    [arr removeObject:dic];
    
    [_allDataDictionary removeObjectForKey:@"Programs"];
    [_allDataDictionary setObject:arr forKey:@"Programs"];
    NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    //
    [user removeObjectForKey:@"AllData"];
    [user setObject:allStr forKey:@"AllData"];
    
    [user synchronize];
    
    if (mod.Id>0) {
        
        if ([user objectForKey:@"deletePlanArray"] !=nil) {
            
            
            NSString* str = [user objectForKey:@"deletePlanArray"];
            //    NSLog(@"eee===%@",str);
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray * allClassArr  = [[NSMutableArray alloc]init];
            allClassArr = [dict objectForKey:@"deletePlanArray"];
            [allClassArr addObject:mod.Id];
            
            [dict removeObjectForKey:@"deletePlanArray"];
            [dict setObject:allClassArr forKey:@"deletePlanArray"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            [user removeObjectForKey:@"deletePlanArray"];
            [user setObject:allStr forKey:@"deletePlanArray"];
            [user synchronize];
            
        }else{
            NSMutableArray * DCA = [[NSMutableArray alloc]init];
            [DCA addObject:mod.Id];
            NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
            [dcd setObject:DCA forKey:@"deletePlanArray"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
            NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            [user setObject:deleteChild forKey:@"deletePlanArray"];
            [user synchronize];
        }
    }
    [_backView removeFromSuperview];
    [self.alertView removeFromSuperview];
    [self.myTableView reloadData];
    
    
}
-(void)pressAlertNo{
    NSLog(@"取消删除");
    [_backView removeFromSuperview];
    [self.alertView removeFromSuperview];
}

#pragma mark  修改名称
-(void)ChangeCLassNameWith:(NSInteger )integer{
//    self.indexPath = [[NSIndexPath alloc]init];
//    self.indexPath = indexpath;
    self.Rinteger = integer;
    PlanModel * model = self.planArray[integer];
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    
    self.changeNameView = [[AddClassOrCNView alloc]init];
    self.changeNameView.remindLabel.text = @"编辑测试计划";
    [self.changeNameView.sureBtn setTitle:@"保存" forState:UIControlStateNormal];
    self.changeNameView.infoTextField.text = model.Title;
    self.changeNameView.infoTextField.delegate = self;
    [window addSubview:self.changeNameView];
    [self.changeNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(window.mas_centerX);
        make.centerY.mas_equalTo(window.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(500*AutoScaleHorizontal, 250*AutoScaleVertical));
    }];
    
    self.changeNameView.planNameLabel = [[UILabel alloc]init];
    self.changeNameView.planNameLabel.text = @"计划名称";
    self.changeNameView.planNameLabel.font =[UIFont systemFontOfSize:20*AutoScaleHorizontal];
    self.changeNameView.planNameLabel.textColor = UIColorFromRGB(81, 81, 81);
    [self.changeNameView addSubview:self.changeNameView.planNameLabel];
    [self.changeNameView.planNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.changeNameView.mas_left).with.offset(75*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.changeNameView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(85*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    self.changeNameView.planStarLabel = [[UILabel alloc]init];
    self.changeNameView.planStarLabel.text = @"*";
    self.changeNameView.planStarLabel.textColor = [UIColor redColor];
    [self.changeNameView addSubview:self.changeNameView.planStarLabel];
    [self.changeNameView.planStarLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.changeNameView.planNameLabel.mas_right).with.offset(35*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.changeNameView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(10*AutoScaleHorizontal, 10*AutoScaleVertical));
    }];
    
    self.changeNameView.infoTextField.layer.borderWidth =1;
    self.changeNameView.infoTextField.layer.borderColor = [UIColor blackColor].CGColor;
    [self.changeNameView.infoTextField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.changeNameView.planStarLabel.mas_right).with.offset(5*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.changeNameView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 40*AutoScaleVertical));
    }];
    
    [self.changeNameView.sureBtn addTarget:self action:@selector(changeSureWithindex:) forControlEvents:UIControlEventTouchUpInside];
    [self.changeNameView.cancelBtn addTarget:self action:@selector(changeCancel) forControlEvents:UIControlEventTouchUpInside];
}

-(void)changeCancel{
    [_backView removeFromSuperview];
    [self.changeNameView removeFromSuperview];
}

//确定修改
-(void)changeSureWithindex:(NSInteger)integer{
    integer = self.Rinteger;
    
    
    if (self.changeNameView.infoTextField.text.length == 0) {
        [self showMessage:@"班级名不能为空"];
    }else{
        
        PlanModel* model = self.planArray[integer];
        model.Title = self.changeNameView.infoTextField.text;
        //        NSLog(@"x");
        [self.planArray replaceObjectAtIndex:integer withObject:model];
        //更新数据源
        NSUserDefaults * user =[NSUserDefaults standardUserDefaults];
        NSMutableArray * arr = [_allDataDictionary objectForKey:@"Programs"];
        NSMutableDictionary * dic = arr[integer];
        if (![[dic objectForKey:@"Title"]isEqualToString:self.changeNameView.infoTextField.text]) {
            [dic setObject:@"1" forKey:@"1900V"];
        }
        [dic removeObjectForKey:@"Title"];
        [dic setObject:self.changeNameView.infoTextField.text forKey:@"Title"];
        [arr replaceObjectAtIndex:integer withObject:dic];
        
        [_allDataDictionary removeObjectForKey:@"Programs"];
        [_allDataDictionary setObject:arr forKey:@"Programs"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
        NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //
        [user removeObjectForKey:@"AllData"];
        [user setObject:allStr forKey:@"AllData"];
        
        [user synchronize];
        [_backView removeFromSuperview];
        [self.changeNameView removeFromSuperview];
        [self.myTableView reloadData];
    }
    
    
}

#pragma mark 左右导航栏按钮方法
-(void)leftBarBtnClicked{
    NSLog(@"左按钮");
    [self.navigationController popViewControllerAnimated:YES];
}
//新建测试
-(void)rightBarBtnClicked{
    NSLog(@"新建测试ING");
//    self.view.backgroundColor = [UIColor whiteColor];
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];

    self.whiteView = [[UIView alloc]init];
    self.whiteView.backgroundColor = [UIColor whiteColor];
    [window addSubview:self.whiteView];
    [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(window.mas_centerX);
        make.centerY.mas_equalTo(window.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(600*AutoScaleHorizontal, 300*AutoScaleVertical));
    }];
    //上方绿色VIEW
    self.greenView = [[UIView alloc]init];
    self.greenView.backgroundColor = UIColorFromRGB(26, 167, 157);
    [self.whiteView addSubview:self.greenView];
    [self.greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.whiteView);
        make.height.mas_equalTo(40*AutoScaleVertical);
    }];
    //添加孩子
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.text = @"新建测试计划";
    self.titleLabel.textColor = [UIColor whiteColor];
    [self.titleLabel setTextAlignment:NSTextAlignmentCenter];
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    [self.greenView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.greenView.mas_centerX);
        make.centerY.mas_equalTo(self.greenView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    //取消按钮
    self.cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cancelBtn setImage:[UIImage imageNamed:@"cancelBtn"] forState:UIControlStateNormal];
    [self.greenView addSubview:self.cancelBtn];
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.titleLabel.mas_centerY);
        make.right.mas_equalTo(self.greenView.mas_right).with.offset(-20*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(20*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];

    
    self.planNameLabel = [[UILabel alloc]init];
    self.planNameLabel.text = @"计划名称:";
    self.planNameLabel.textColor = [UIColor blackColor];
    [self.planNameLabel setTextAlignment:NSTextAlignmentLeft];
    self.planNameLabel.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [self.whiteView addSubview:self.planNameLabel];
    [self.planNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.greenView.mas_bottom).with.offset(50*AutoScaleVertical);
        make.left.mas_equalTo(self.whiteView.mas_left).with.offset(75*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    _red1 = [[UILabel alloc]init];
    _red1.textColor =[UIColor redColor];
    _red1.text = @"*";
    _red1.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [self.whiteView addSubview:self.red1];
    [self.red1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.planNameLabel.mas_right).with.offset(60*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.planNameLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(15*AutoScaleHorizontal, 15*AutoScaleVertical));
    }];
    
    self.planTextField = [[UITextField alloc]init];
    //    self.nameText.delegate =self;
    self.planTextField.layer.borderWidth = 1;
    self.planTextField.placeholder = @"在此输入计划名称";
    self.planTextField.layer.borderColor =UIColorFromRGB(243, 243, 243).CGColor;
    [self.whiteView addSubview:self.planTextField];
    [self.planTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.red1.mas_right).with.offset(5*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.planNameLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(250*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    self.teacherNameLabel = [[UILabel alloc]init];
    self.teacherNameLabel.text = @"负责教师:";
    self.teacherNameLabel.textColor = [UIColor blackColor];
    [self.teacherNameLabel setTextAlignment:NSTextAlignmentLeft];
    self.teacherNameLabel.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [self.whiteView addSubview:self.teacherNameLabel];
    [self.teacherNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.planNameLabel.mas_bottom).with.offset(40*AutoScaleVertical);
        make.left.mas_equalTo(self.whiteView.mas_left).with.offset(75*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    _red2 = [[UILabel alloc]init];
    _red2.textColor =[UIColor redColor];
    _red2.text = @"*";
    _red2.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [self.whiteView addSubview:self.red2];
    [self.red2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.teacherNameLabel.mas_right).with.offset(60*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.teacherNameLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(15*AutoScaleHorizontal, 15*AutoScaleVertical));
    }];
    
    self.teacherTextField = [[UITextField alloc]init];
    //    self.nameText.delegate =self;
    self.teacherTextField.layer.borderWidth = 1;
    self.teacherTextField.placeholder = @"输入教师名称";
    self.teacherTextField.layer.borderColor =UIColorFromRGB(243, 243, 243).CGColor;
    [self.whiteView addSubview:self.teacherTextField];
    [self.teacherTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.red2.mas_right).with.offset(5*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.teacherNameLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(250*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    //确定按钮
    self.confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmBtn.backgroundColor =UIColorFromRGB(26, 167, 157);
    self.confirmBtn.layer.cornerRadius = 5;
    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [self .whiteView addSubview:self.confirmBtn];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView. mas_centerX);
        make.top.mas_equalTo(self.teacherNameLabel.mas_bottom).with.offset(60*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(70*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    [self.cancelBtn addTarget:self action:@selector(pressCancel) forControlEvents:UIControlEventTouchUpInside];
    [self.confirmBtn addTarget:self action:@selector(pressConfirm) forControlEvents:UIControlEventTouchUpInside];
   
}
//取消添加
-(void)pressCancel{
    [_backView removeFromSuperview];
    [self.whiteView removeFromSuperview];
}
//确定添加
-(void)pressConfirm{
    
    
    if (self.planTextField.text.length == 0) {
        [self showMessage:@"计划名称不能为空"];
    }
    else if (self.teacherTextField.text.length == 0) {
        [self showMessage:@"负责教师不能为空"];
    }else{
        
        //获取当前时间
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSDate *datenow = [NSDate date];
        NSString *currentTimeString = [formatter stringFromDate:datenow];
        NSString * currentTime = [currentTimeString substringWithRange:NSMakeRange(0, 10)];
    
        
        NSUserDefaults  * user = [NSUserDefaults standardUserDefaults];
        NSInteger newplanID = [[user objectForKey:@"CreatPlanId"]integerValue]-1 ;
        NSNumber * newPlan = [NSNumber numberWithInt:newplanID];
        
        [user removeObjectForKey:@"CreatPlanId"];
        [user setObject:newPlan forKey:@"CreatPlanId"];
        
        NSMutableDictionary * newPlanDic = [[NSMutableDictionary alloc]init];
        [newPlanDic setObject:self.teacherTextField.text forKey:@"CreateTeacher"];
        [newPlanDic setObject:self.planTextField.text forKey:@"Title"];
        [newPlanDic setObject:[user objectForKey:@"AgencyId"] forKey:@"ServiceUnitId"];
        [newPlanDic setObject:currentTime forKey:@"CreateTime"];
        [newPlanDic setObject:@1 forKey:@"Type"];
        NSNumber * falsenum = [NSNumber numberWithBool:NO];
        [newPlanDic setObject:falsenum forKey:@"Status"];
        [newPlanDic setObject:newPlan forKey:@"Id"];
    
        NSMutableArray * arr = [_allDataDictionary objectForKey:@"Programs"];
        [arr insertObject:newPlanDic atIndex:0];
//        [arr addObject:newPlanDic];
        [_allDataDictionary removeObjectForKey:@"Programs"];
        [_allDataDictionary setObject:arr forKey:@"Programs"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
        NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //
        [user removeObjectForKey:@"AllData"];
        [user setObject:allStr forKey:@"AllData"];
        [user setObject:@"yes" forKey:@"ValueChanged"];
        [user synchronize];

        
    [_backView removeFromSuperview];
    [self.whiteView removeFromSuperview];
    
    BeginNewPlanViewController * bvc = [[BeginNewPlanViewController alloc]init];
    bvc.planModel = [PlanModel modelWithDictionary:newPlanDic];
    [self.navigationController pushViewController:bvc animated:YES];
    }
}


#pragma mark ---- 根据键盘高度将当前视图向上滚动同样高度
///键盘显示事件
- (void)keyboardWillShoww:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = kbHeight;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            window.frame = CGRectMake(0.0f, -85*AutoScaleVertical, window.frame.size.width, window.frame.size.height);
        }];
    }
}

#pragma mark ---- 当键盘消失后，视图需要恢复原状
///键盘消失事件
- (void)keyboardWillHidee:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [UIView animateWithDuration:duration animations:^{
        window.frame = CGRectMake(0, 0, window.frame.size.width, window.frame.size.height);
    }];
}
// 释放
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
